package com.refid.api.thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import com.refid.api.cmd.Cmd;
import com.refid.api.exception.MsgException;
import com.refid.api.hander.ReadHander;
import com.refid.api.util.BuleUtil;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

public class RfidBluetooth {
	private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP服务UUID号
	private BluetoothAdapter bluetoothAdapter;
	private BluetoothSocket socket;
	private BuleReadThread buleReadThread = null;
	private ReadHander hander;// 标签读取后处理
	private Cmd cmd = null;
	private Integer readTimeOut;

	public RfidBluetooth(BluetoothAdapter bluetoothAdapter, Cmd cmd, ReadHander hander, Integer readTimeOut) {
		// BluetoothAdapter.getDefaultAdapter()
		this.bluetoothAdapter = bluetoothAdapter;
		this.hander = hander;
		this.cmd = cmd;
		this.readTimeOut = readTimeOut;
	}

	public boolean start(String address) throws MsgException {
		if (bluetoothAdapter.isEnabled() == false) {
			bluetoothAdapter.enable();
			// BuleUtil.sleep(8 * 1000);
		}
		BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
		InputStream is = null;
		try {
			socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
		} catch (IOException e) {
			BuleUtil.close(socket);
			socket = null;
			throw new MsgException("读取蓝牙设备失败！", e);
		}

		try {
			if (socket != null) {
				socket.connect();
			}
		} catch (IOException e) {
			BuleUtil.close(socket);
			socket = null;
			throw new MsgException("连接蓝牙失败！", e);
		}

		try { // 得到蓝牙数据输入流
			is = socket.getInputStream();
		} catch (IOException e) {
			close();
			throw new MsgException("读取蓝牙数据失败！", e);
		}
		buleReadThread = new BuleReadThread(is, cmd, hander, readTimeOut);
		buleReadThread.start();
		return true;
	}

	public void close() {
		BuleUtil.close(socket);
		if (buleReadThread != null) {
			BuleUtil.close(buleReadThread.getIs());
			buleReadThread.setIs(null);
		}
		socket = null;
	}

	public void senCmd(String hexCmd) throws MsgException {
		OutputStream os = null;
		try {
			os = socket.getOutputStream(); // 蓝牙连接输出
			byte[] bos = cmd.toSendByte(hexCmd);
			os.write(bos);
		} catch (IOException e) {
			throw new MsgException("向蓝牙发送信息失败", e);
		}
	}

	public boolean isStop() {
		return buleReadThread == null || buleReadThread.getIs() == null;
	}
}
